package com.sz.common.core.system.service.impl;

import com.sz.common.base.service.AbstractService;
import com.sz.common.core.system.entity.SysSMS;
import com.sz.common.core.system.service.SysSmsService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Johnboy <br>
 * Date: 2017-08-10 13:55:00
 */
@Service
public class SysSmsServiceImpl extends AbstractService implements SysSmsService {

    @Override
    protected String getMapperNamespace() {
        return "com.sz.common.core.system.SysSMSMapper";
    }

    @Override
    public int createSMS(String phoneNumber, String phoneKey, String phoneCode) {
        SysSMS sysSMS = new SysSMS();
        sysSMS.setBody(phoneKey);
        sysSMS.setPhone(phoneNumber);
        sysSMS.setTemplateCode(phoneCode);
        this.dao.save(this.getSqlName("insertSelective"), sysSMS);
        return sysSMS.getId();
    }

    @Override
    public void updateSendResult(int id, boolean result, String errorCode) {
        SysSMS sysSMS = getSmsById(id);
        if (sysSMS != null) {
            if (result) {
                sysSMS.setIsSent(true);
                sysSMS.setSendTime(new Date());
            }
            else {
                sysSMS.setRetry(sysSMS.getRetry() + 1);
                sysSMS.setSendTime(new Date());
                sysSMS.setErrorCode(errorCode);
            }
            this.dao.update(this.getSqlName("updateByPrimaryKeySelective"), sysSMS);
        }
    }

    @Override
    public List<SysSMS> getAllNeddSendSMS() {
        List<SysSMS> needSendSMS = this.dao.findForList(this.getSqlName("selectNotSendMails"), null, SysSMS.class);
        return needSendSMS;

    }

    @Override
    public SysSMS getSmsById(int id) {
        return (SysSMS) this.dao.findForObject(getSqlName("selectById"), id);
    }

    @Override
    public void setSmsFailStatus(int id, String errorCode) {
        SysSMS sysSMS = getSmsById(id);
        if (sysSMS != null) {
            sysSMS.setRetry(10);
            sysSMS.setSendTime(new Date());
            sysSMS.setErrorCode(errorCode);
            this.dao.update(this.getSqlName("updateByPrimaryKeySelective"), sysSMS);
        }
    }
}
